import { doubleValidate, validatePhone, mapVerification} from '~/utils/validate.js'
import {mapGetters} from "vuex"
import BaseLoad from '@/assets/vue-mixin/BaseLoad'
import positionDialog from '@/components/positionDialog'
import supportFacilityInformation from '../../project-acceptance/newEdit/supporting-facilities-information'
import { validateLandCode } from "~/views/property-plan-sys/property-plan-manage/planning-property/api/planning.js"
import {validateProject} from "~/views/property-plan-sys/property-plan-manage/projects-under-construction/api/construction";
import {get, save, update, delFiles, removeFacById, initMilestones, validateProjectCountryCode} from '../api/project_manage'
import {checkFiles} from '@/api/operate-construction-contract'
import vPdf from '@/components/v-pdf'
import { download } from "@/admin/api/common"
import { downloadBlob } from "@/utils"

export default {
    name: "project_form",
    mixins: [BaseLoad],
    created() {
        let routeParamId = this.$route.query.projectId
        if(routeParamId){
            this.isAdd = false
            this.addSource = true
            this.isEdit = routeParamId
            this.initCitySelector()
        }
        this.projectStreet = this.getDict('streets')
        this.communityNames = this.getDict('community_names')
        this.landUses = this.getDict('land_uses')
        this.projectType = this.getDict('project_types')
        this.manageUnits = this.getDict('administrative_office')
        this.propertyTypes = this.getDict("property_types")
        this.propertyUseTypes = this.getDict("property_use_types")
        this.transferModeOption = this.getDict("transfer_types")
        this.propForm.landInfo.cityCode = this.cityAssembly[0].value
        this.propForm.landInfo.countyCode = this.districtCollection[0].value
        if (!this.isEdit) {
            let obj = {
                tempId: this.propForm.propertyBasic.isUpdate,
                projectId: ''
            }
            this.handleClickToUpdateItem(obj)
            // hxf-0910-tab选中项
            this.handleClick({index: 0}, null)
        }
    },
    computed: {
        ...mapGetters({
            cityAssembly: 'getCityAssembly',
            districtCollection: 'getDistrictCollection',
        })
    },
    filters: {
        ellipsis(value) {
            if (!value) {
                return ''
            } else if (value.length > 6) {
                return value.slice(0,6) + '...'
            } else {
                return value
            }
        }
    },
    watch: {
        'propForm.propertyBasic.isUpdate': function () {
            if (this.isThereAMilestone === this.propForm.propertyBasic.isUpdate) {
                let obj = {
                    tempId: this.propForm.propertyBasic.isUpdate,
                    projectId: this.projectId
                }
                if (this.addSource === false) {
                    this.handleClickToUpdateItem(obj)
                }
            } else {
                let obj = {
                    tempId: this.propForm.propertyBasic.isUpdate,
                    projectId: ''
                }
                if (this.addSource === false) {
                    this.handleClickToUpdateItem(obj)
                }
            }
        },
        'propForm.projectMilestones': {
            deep: true,
            handler(val) {
                let index = val.findIndex(item => {
                    return item.materialsFormVoList.some(it => it.isRequired !== '0' && !it.fileBusId)
                })
                if (index === -1) {
                    this.activeIndex = val.length - 1
                } else {
                    this.activeIndex = index
                }
                if(val){
                    this.propForm.propertyBasic.stage = val[this.activeIndex].milestoneName
                }
                // 里程碑一级文件上传后带到二级文件显示
                let flieBusId = '', original = '', flieBus = '', origin = ''
                val.map(item => {
                    item.materialsFormVoList.forEach(it => {
                            this.$nextTick(() => {
                                    //如果当前材料是复用上一级且当前里程碑不是第一个
                                    if (it.isReuse !== '0' && index > 0) {
                                        //    从上级里程碑信息中查询该材料清单名称的信息
                                        let mater = val[index - 1]
                                        if (mater && mater.materialsFormVoList instanceof Array) {
                                            let find = mater.materialsFormVoList.find(f => f.materialsName == it.materialsName);
                                            if (find) {
                                                //查询到了，这将查询到的材料清单的文件赋值给当前材料清单
                                                it.fileBusId = find.fileBusId
                                                it.original = find.original
                                            }
                                        }
                                    }

                                }
                            )
                        }
                    )
                })
            }
        }
    },
    components: {
        positionDialog,
        supportFacilityInformation,
        vPdf
    },
    data() {
        return {
            propForm: {
                landInfo: {
                    parcelNum: '',
                    parcelArea: '',
                    landUse: '',
                    cityCode: '',
                    countyCode: '',
                    street: '',
                    community: '',
                    addressInfo: ''
                },
                propertyBasic: {
                    projectCode: '',
                    projectName: '',
                    projectArea: '',
                    projectType: '',
                    manageUnit: '',
                    isUpdate: '2',
                    constructionUnit: '',
                    contactName: '',
                    contactPhone: '',
                    stage: '',
                    mapCoordinates: '',
                    remarks: '',
                    projectCountryCode: ''
                },
                supportingFacilities: [],
                projectMilestones: []
            },
            isEdit: '' ,
            projectId: '' ,
            isThereAMilestone: '' ,
            selected: '',
            activeIndex: 0,
            milestoneSort: '1',
            milestoneSortIndex: 0,
            addSource: false,
            isAdd: true,
            bulletInformationFlag: true,
            editDataShow: false,
            dialogVisibleView: false,
            // 预览弹窗展示的类型
            previewType: '',
            // 预览文件的地址
            previewUrl: '',
            url: '/admin/sys-file/upLodeFileAdd',
            busId: '',
            modelType: 'milestone',
            isUpload: [],
            httpRequestFileLis: [],
            multipleSelection: [],
            projectStreet: [],
            landUses: [],
            communityNames: [],
            communityNameStreet: [],
            projectType: [],
            manageUnits: [],
            propertyTypes: [],
            propertyUseTypes: [],
            transferModeOption: [],
            httpRequestData: {},
            landInfo_rules: {
                parcelNum: [
                    {required: true, message: "请输入宗地号", trigger: "blur"},
                    {min: 0, max: 30, message: "长度在0-30个字符串", trigger: "blur"}
                ],
                parcelArea: [
                    {required: true, message: "请输入宗地面积(m²)", trigger: "blur"},
                    { validator: doubleValidate, trigger: "blur" }
                ],
                landUse: [
                    {required: true, message: "请选择土地用途", trigger: "blur"}
                ],
                cityCode: [
                    {required: true, validator: (rules, value, callback) => {
                            //区县
                            let county = this.propForm.landInfo.countyCode
                            //   街道
                            let street = this.propForm.landInfo.street
                            //   社区
                            let community = this.propForm.landInfo.community
                            //   管理所
                            let addressInfo = this.propForm.landInfo.addressInfo
                            if(!value || !county || !street || !community || !addressInfo){
                                return callback(new Error("物业地址不能为空"))
                            }
                            return callback()
                        },  trigger: "blur"}
                ],
                addressInfo: [
                    {required: true, message: "地址不能为空", trigger: "blur"},
                    {min: 0, max: 50, message: "长度在0-50个字符串", trigger: "blur"}
                ]
            },
            propertyBasic_rules: {
                projectName: [
                    { required: true, message: "请输入项目名称", trigger: "blur" },
                    { min: 0, max: 30, message: "长度在0-30个字符串", trigger: "blur" },
                ],
                projectArea: [
                    { required: true, message: "请输入项目面积", trigger: "blur" },
                    { validator: doubleValidate, trigger: "blur" },
                ],
                contactPhone: [
                    { required: false},
                    { validator: validatePhone, trigger: "blur" }
                ],
                projectType: [
                    { required: true, message: "请输入项目类型", trigger: "blur" },
                    { min: 0, max: 30, message: "长度在0-30个字符串", trigger: "blur" },
                ],
                manageUnit: [
                    { required: true, message: "请输入管理权属", trigger: "blur" }
                ],
                mapCoordinates: [
                    { required: true, message: "请输入地图坐标", trigger: "blur" },
                    { min: 0, max: 30, message: "长度在0-30个字符串", trigger: "blur" },
                    { validator: mapVerification, trigger: "blur" }
                ],
                projectCountryCode: [
                    { required: true, message: "请输入项目国家编号", trigger: "blur" },
                    { min: 0, max: 100, message: "长度在0-100个字符串", trigger: "blur" }
                ],
            },
        }
    },
    methods: {
        validateProjectCountryCode(value) {
            validateProjectCountryCode( value, this.projectId || '').then(res => {
                if (res.data.data !== 0) {
                    this.$message.error("项目国家编码已存在，请重新输入")
                    this.propForm.propertyBasic.projectCountryCode = ''
                }
            })
        },
        //社区联动
        initCommunityName(){
            this.communityNameStreet.length = 0;
            let selectStreet = this.propForm.landInfo.street
            if(selectStreet != '' &&  this.communityNames != null &&  this.communityNames.length > 0){
                this.communityNameStreet = this.communityNames.filter(cn => cn.value.indexOf(selectStreet) != -1)
            }
        },
        //改变宗地号
        landCodeOnly(value) {
            validateLandCode({"landCode": value, "landId": this.propForm.landInfo.landId || ''}).then(res => {
                if (res.data.data !== 0) {
                    this.$message.warning("宗地号已存在，请确认是否继续操作")
                }
            })
        },
        //选择区
        handleChangeCountyCode() {
            this.propForm.landInfo.street = ''
            this.propForm.landInfo.community = ''
        },
        //选择街道
        handleChangeStreet() {
            this.propForm.landInfo.community = ''
            this.initCommunityName();
        },
        //选择道路及门牌号
        handleValidateProject(value) {
            if (this.propForm.landInfo.cityCode === '' || this.propForm.landInfo.countyCode === ''
                || this.propForm.landInfo.street === '' || this.propForm.landInfo.community === ''){
                this.$message.error('请将市区街道社区填写完整后再填写详细地址！')
                this.propForm.landInfo.addressInfo = ''
            } else {
                let areaCode = this.propForm.landInfo.cityCode + "-" +
                    this.propForm.landInfo.countyCode + "-" +
                    this.propForm.landInfo.street + "-" +
                    this.propForm.landInfo.community
                validateProject({'addressInfo': value, 'areaCode': areaCode}).then(res => {
                    if (res.data.data === 2) {
                        this.$message.warning('该地址已存在！')
                    }
                })
            }
        },
        //选择地图坐标
        resetPosition(data) {
            let position = JSON.parse(data)
            if(position.length) {
                this.propForm.propertyBasic.mapCoordinates = position.join(',')
            }
        },
        //配套信息添加
        superInforAdd() {
            this.editDataShow = true
            this.$nextTick(() => {
                this.$refs.supportFacilityInformation.showDialog()
            })
            this.bulletInformationFlag = true
            this.bulletInformationIndex = 0
        },
        //配套信息编辑
        handleClickEdit(item) {
            this.editDataShow = true
            this.$nextTick(() => {
                this.$refs.supportFacilityInformation.showDialog(item)
            })
            this.bulletInformationFlag = false
            this.bulletInformationIndex = item.$index
        },
        //配套信息删除
        handleClickDelete(index,rows) {
            if (rows[index].facilitiesId) {
                this.$confirm('此操作将永久删除该条数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    removeFacById(rows[index].facilitiesId).then(resp => {
                        if (resp.data.code === 0) {
                            rows.splice(index, 1)
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            })
                        } else {
                            this.$message({
                                type: 'error',
                                message: '删除失败!'
                            })
                        }
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    })
                })
            } else {
                rows.splice(index, 1)
            }
        },
        //配套信息保存
        handleDialogsSave(item) {
            if (this.bulletInformationFlag) {
                this.propForm.supportingFacilities.push(item.arr)
            } else {
                this.propForm.supportingFacilities[this.bulletInformationIndex] = item.arr
            }
            this.handleClose()
        },
        //切换资料信息tab
        handleClick(tab, event) {
            this.isUpload = []
            this.selected = tab.index
            // 如果文件busid为空那么就可以上传
            if (this.propForm.projectMilestones[tab.index]) {
                this.propForm.projectMilestones[tab.index].materialsFormVoList.map((item, index) => {
                    if (item.fileBusId === null || item.fileBusId === '' || item.fileBusId === undefined) {
                        this.isUpload.push(true)
                    } else if (item.isReuse === '1') {
                        this.isUpload.push(false)
                    } else {
                        this.isUpload.push(false)
                    }
                });
            } else {
                this.isUpload.push(true)
            }
        },
        // 是否为默认项目，默认选择否
        handleClickToUpdateItem(obj) {
            initMilestones(obj).then(res => {
                if (res.data.code === 0) {
                    this.propForm.projectMilestones = res.data.data
                    let materialsNameRequired = `<span style="color: #f66c6c">*</span>`
                    this.propForm.projectMilestones.map(item => {
                        item.materialsFormVoList.map(i => {
                            if (i.isRequired === '1') {
                                i.materialsName += materialsNameRequired
                            }
                        })
                    })
                    // 新增回显初始化加载自动点击tabs第一个
                    this.handleClick({index: 0}, null)
                    this.$forceUpdate()
                } else {
                    this.$message.error('未获取到里程碑信息！')
                }
            })
        },
        //资料信息选择序号列表
        handleSelectionChange(val) {
            this.multipleSelection = val
        },
        // 调用移除文件
        triggerBeforeRemove(item) {
            this.beforeRemove(item)
        },
        // 移除文件
        beforeRemove(file) {
            this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                delFiles(file.row.fileBusId, this.modelType).then(resp => {
                    if (resp.data.code === 0) {
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        })
                        file.row.original = ''
                        file.row.fileBusId = ''
                        this.isUpload[file.$index] = true
                    } else {
                        this.$message({
                            type: 'error',
                            message: '删除失败!'
                        })
                    }
                })

            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                })
            })
        },
        // PDF预览\文件下载
        triggerBeforeDownload(item) {
            if (item.row.fileId === null) {
                this.$message.warning('文件暂未上传到服务器，无法下载！')
            } else {
                if (item.row.original.split('.')[1] === 'pdf') {
                    checkFiles(item.row.fileId).then(res => {
                        if (res.data.code === 0) {
                            this.previewType = 'pdf'
                            this.previewUrl = item.row.fileId
                            this.dialogVisibleView = true
                        } else {
                            this.$message.warning('文件不存在或已删除！')
                        }
                    })
                } else if (item.row.original.split('.')[1] === 'jpg' || item.row.original.split('.')[1] === 'png' || item.row.original.split('.')[1] === 'jpeg') {
                    checkFiles(item.row.fileId).then(res => {
                        if (res.data.code === 0) {
                            this.previewType = 'image'
                            this.previewUrl = '/admin/sys-file/img/' + item.row.fileId
                            this.dialogVisibleView = true
                        } else {
                            this.$message.warning('文件不存在或已删除！')
                        }
                    })
                } else {
                    checkFiles(item.row.fileId).then(res =>{
                        if (res.data.code === 0) {
                            download('/admin/sys-file/download/' + item.row.fileId, this.modelType).then(response => {
                                downloadBlob(response.data, item.row.original)
                            })
                        } else {
                            this.$message.warning('文件不存在或已删除！')
                        }
                    })
                }
            }
        },
        // 文件上传
        httpRequest(params,row){
            try {
                if (params.file.size > (10 * 1024 * 1024)) {
                    this.$message({
                        type: 'error',
                        message: `上传文件大小不能超过 10MB!`,
                    });
                    return
                }
                let format = ["jpg","jpeg","png","gif","bmp","wmv","mpeg","mp4","doc","docx","xls","xlsx","ppt","pptx","txt","pdf"]
                let formatType = params.file.name.split('.')[1]
                if (format.indexOf(formatType) === -1) {
                    this.$message.error('文件上传不支持该格式文件，目前仅支持\'jpg,jpeg,png,gif,bmp,wmv,mpeg,mp4,doc,docx,xls,xlsx,ppt,pptx,txt,pdf\'格式文件！')
                    return
                }
                //  用FormData存放上传文件
                let formData = new FormData();
                formData.append('file', params.file)
                formData.append('module', this.modelType)
                if (this.busId) {
                    formData.append('busId', busId)
                }
                this.http.post(this.url, formData).then(resp =>{
                    if (resp.data.code === 0) {
                        row.row.original = params.file.name
                        row.row.fileBusId = resp.data.data
                        this.isUpload[row.$index] = false
                    } else {
                        this.$message.error('文件上传失败！')
                    }
                })
            }catch (e) {
                console.log(e)
            }
        },
        //对应value取label
        getCardTypeValue(num, sum){
            let arr = sum.filter(e=>e.value === num)
            if (arr.length > 0) {
                return arr[0].label
            } else {
                return num
            }
        },
        //关闭当前新增页
        closeNowRouter() {
            //关闭当前新增页，暂时没找到好办法
            this.$store.commit("delHistoryRoute", this.$route.fullPath);
            // this.$parent.$children[2].closeTab('current')
            //跳转
            this.$router.push("/property-info-sys/project-manage");
        },
        // 初始化
        initCitySelector() {
            const loading = this.$loading({
                lock: true,
                text: '数据加载中'
            });
            get(this.isEdit).then((rep) => {
                this.isAdd = false
                if (rep.data.data.propertyBasic !== null) {
                    this.propForm.propertyBasic = rep.data.data.propertyBasic
                    this.projectId = rep.data.data.propertyBasic.projectId
                    /*if (this.propForm.propertyBasic.addSource === '1') {
                        this.addSource = false
                    }*/
                }
                if (rep.data.data.projectMilestones !== null) {
                    this.propForm.projectMilestones = rep.data.data.projectMilestones
                    if(this.propForm.projectMilestones.length > 0){
                        this.milestoneSortIndex = this.propForm.projectMilestones.findIndex(pm => pm.milestoneName == this.propForm.propertyBasic.stage)
                        if(this.milestoneSortIndex === -1){
                            this.milestoneSortIndex = 0
                        }
                        this.milestoneSort = (this.milestoneSortIndex+1).toString();
                    }
                    this.handleClick({index: this.milestoneSortIndex}, null )
                }
                if (rep.data.data.landInfo !== null) {
                    this.propForm.landInfo = rep.data.data.landInfo
                    this.initCommunityName()
                }
                if (rep.data.data.supportingFacilities !== null) {
                    this.propForm.supportingFacilities = rep.data.data.supportingFacilities
                }
                this.$set(this.propForm.propertyBasic,'manageUnit',rep.data.data.manageUnit)
                this.$set(this.propForm.propertyBasic,'mapCoordinates',rep.data.data.mapCoordinates)
                this.isThereAMilestone = rep.data.data.propertyBasic.isUpdate
                this.projectId = rep.data.data.propertyBasic.projectId
                loading.close()
            }).catch((e) => {
                console.log(e)
                loading.close()
                this.$message({
                    type: "error",
                    message: "数据获取失败!",
                });
            });

        },
        //关闭弹框组件
        handleClose() {
            this.editDataShow = false
        },
        //保存
        handlePreservation() {
            const landInfo = new Promise((resolve, reject) => {
                this.$refs['landInfo'].validate((valid) => {
                    if (valid) resolve();
                })
            })

            const propertyBasic = new Promise((resolve, reject) => {
                this.$refs["propertyBasic"].validate(
                    (valid) => {
                        if (valid) resolve();
                    }
                );
            })
            Promise.all([landInfo,propertyBasic]).then(() => {
                //文件上传
                /*if (this.propForm.projectMilestones[this.selected].materialsFormVoList.some(it =>
                    it.isRequired !== '0' && !it.fileBusId)) return this.$message.error('请上传必填文件！')*/

                let areaCode = this.propForm.landInfo.cityCode + "-" +
                    this.propForm.landInfo.countyCode + "-" +
                    this.propForm.landInfo.street + "-" +
                    this.propForm.landInfo.community
                this.propForm.manageUnit = this.propForm.propertyBasic.manageUnit
                this.propForm.mapCoordinates = this.propForm.propertyBasic.mapCoordinates
                validateProject({'addressInfo': this.propForm.landInfo.addressInfo,
                    'areaCode': areaCode,
                    'propertyName': this.propForm.propertyBasic.projectName,
                    'projectId': this.projectId}).then(res => {
                    if (res.data.data === 1) {
                        this.$message.error('该地址下的项目名称已存在，请重新输入！')
                    } else {
                        this.loadAction("保存中")
                        if (this.isAdd) {
                            save(this.propForm).then(res => {
                                this.loadClose()
                                this.$message.success('保存成功！')
                                this.closeNowRouter();
                            }).catch((e) => {
                                console.log(e)
                                this.loadClose()
                                this.$message.error("保存失败！");
                            })
                        } else {
                            update(this.propForm).then(res => {
                                this.loadClose()
                                this.$message.success('保存成功！')
                                this.closeNowRouter();
                            }).catch((e) => {
                                console.log(e)
                                this.loadClose()
                                this.$message.error("保存失败！");
                            })
                        }
                    }
                })
            })
        }
    }
}
